from sanic import Sanic
from sanic import response
import json
import time
from sanic.exceptions import NotFound

import sys
sys.path.append("../")
sys.path.append(".")
from parse import args
from helper import ModelServer
from predicter import CommonPredicter


app = Sanic(__name__)

@app.exception(NotFound)
async def url_404(request, excep):
    return response.json({"Error":excep})

@app.route('/ExamServer',methods=['POST'])
async def model_server(request):
    try:
        request_json = request.body
        input_json = json.loads(request_json.decode('utf8'))

        predicter = CommonPredicter.init(args)
        server = ModelServer(predicter=predicter, args=args)
        
        result = server.get_result(input_json)
    except Exception as e:
        result = {"code": 400, "message": "预测失败", "Error": e}
    return response.json(result)

# http://127.0.0.1:6060/predict?text="你好啊"
@app.route('/predict')
async def predict(request):
    text = request.args.get('text', "hello")
    try:
        predicter = CommonPredicter.init(args)
        server = ModelServer(predicter=predicter, args=args)
        result = server.get_result_of_text(text)
    except ValueError:
        result = {"code": 400, "message": "预测失败", "Error": e}
    return response.json(result)

if __name__ == '__main__':
    app.run(host=args.ip,port=args.port)